package com.ustc.hewei.shopmodule.serviceImpl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ustc.hewei.commonmodule.dto.LogicExpireData;
import com.ustc.hewei.commonmodule.dto.Result;
import com.ustc.hewei.commonmodule.entity.Shop;
import com.ustc.hewei.commonmodule.mapper.ShopMapper;
import com.ustc.hewei.commonmodule.service.IShopService;
import com.ustc.hewei.nettyrpc2_0.common.annotation.RPCService;
import com.ustc.hewei.shopmodule.utils.ShopCache;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayDeque;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.ustc.hewei.shopmodule.utils.Constants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hewei
 * @since 2022-10-05
 */
@Service
@RPCService(value = IShopService.class)
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private ShopCache shopCache;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        Shop shop = shopCache.queryWithLogicExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        boolean isSuccess = updateById(shop);
        if (isSuccess) {
            stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        }
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        Page<Shop> shopPage = query()
                .eq("type_id", typeId)
                .page(new Page<>(current, SHOP_MAX_PAGE));
        return Result.ok(shopPage.getRecords());
    }

    @Override
    public void addAllShopToCache() {
        List<Shop> shopList = query().list();
        for (Shop shop : shopList) {
            LogicExpireData<Shop> logicExpireData = new LogicExpireData<>();
            logicExpireData.setData(shop).setLogicTTL(LocalDateTime.now()
                    .plusSeconds(TimeUnit.MINUTES.toSeconds(CACHE_SHOP_TTL)));
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + shop.getId(), JSONUtil.toJsonStr(logicExpireData));
        }
    }

    @Override
    public Result queryByNameLike(String name, Integer current) {
        Page<Shop> shopPage = query().like(StrUtil.isNotBlank(name), "name", name).page(new Page<>(current, SHOP_NAME_MAX_PAGE));
        return Result.ok(shopPage.getRecords());
    }
}
